package view;

import model.Grade;
import model.Class;
import model.Subject;
import model.User;
import service.ClassService;
import service.GradeService;
import service.SubjectService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GradeStatisticsPanel extends JPanel {
    private User currentUser;
    private GradeService gradeService;
    private ClassService classService;
    private SubjectService subjectService;
    private JComboBox<String> classComboBox;
    private JComboBox<String> subjectComboBox;
    private JComboBox<String> examTypeComboBox;
    private JTable statsTable;
    private DefaultTableModel tableModel;
    private Map<String, Integer> classIdMap = new HashMap<>();
    private Map<String, Integer> subjectIdMap = new HashMap<>();
    
    public GradeStatisticsPanel(User currentUser) {
        this.currentUser = currentUser;
        this.gradeService = new GradeService();
        this.classService = new ClassService();
        this.subjectService = new SubjectService();
        initComponents();
        loadData();
    }
    
    private void initComponents() {
        setLayout(new BorderLayout());
        
        // 顶部控制面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        // 班级选择
        controlPanel.add(new JLabel("班级："));
        classComboBox = new JComboBox<>();
        classComboBox.addActionListener(e -> loadSubjects());
        controlPanel.add(classComboBox);
        
        // 课程选择
        controlPanel.add(new JLabel("课程："));
        subjectComboBox = new JComboBox<>();
        subjectComboBox.addActionListener(e -> loadData());
        controlPanel.add(subjectComboBox);
        
        // 考试类型选择
        controlPanel.add(new JLabel("考试类型："));
        examTypeComboBox = new JComboBox<>(
            new String[]{"全部", "期中考试", "期末考试", "单元测试", "模拟考试"}
        );
        examTypeComboBox.addActionListener(e -> loadData());
        controlPanel.add(examTypeComboBox);
        
        add(controlPanel, BorderLayout.NORTH);
        
        // 统计表格
        String[] columnNames = {
            "统计项", "人数/比例", "最高分", "最低分", "平均分", "及格率"
        };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        statsTable = new JTable(tableModel);
        statsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 设置表格列宽
        TableColumnModel columnModel = statsTable.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(150);
        columnModel.getColumn(1).setPreferredWidth(100);
        columnModel.getColumn(2).setPreferredWidth(80);
        columnModel.getColumn(3).setPreferredWidth(80);
        columnModel.getColumn(4).setPreferredWidth(80);
        columnModel.getColumn(5).setPreferredWidth(80);
        
        add(new JScrollPane(statsTable), BorderLayout.CENTER);
        
        // 加载班级数据
        loadClasses();
    }
    
    private void loadClasses() {
        classComboBox.removeAllItems();
        classIdMap.clear();
        
        List<Class> classes;
        if ("ADMIN".equals(currentUser.getRole())) {
            classes = classService.getAllClasses();
        } else {
            classes = classService.getTeacherClasses(currentUser.getId());
        }
        
        for (Class cls : classes) {
            classComboBox.addItem(cls.getClassName());
            classIdMap.put(cls.getClassName(), cls.getId());
        }
    }
    
    private void loadSubjects() {
        String selectedClass = (String) classComboBox.getSelectedItem();
        if (selectedClass == null) return;
        
        subjectComboBox.removeAllItems();
        subjectIdMap.clear();
        
        Integer classId = classIdMap.get(selectedClass);
        List<Subject> subjects = subjectService.getSubjectsByClassId(classId);
        
        for (Subject subject : subjects) {
            subjectComboBox.addItem(subject.getSubjectName());
            subjectIdMap.put(subject.getSubjectName(), subject.getId());
        }
    }
    
    private void loadData() {
        tableModel.setRowCount(0);
        
        String selectedClass = (String) classComboBox.getSelectedItem();
        String selectedSubject = (String) subjectComboBox.getSelectedItem();
        String examType = (String) examTypeComboBox.getSelectedItem();
        
        if (selectedClass == null || selectedSubject == null) return;
        
        Integer classId = classIdMap.get(selectedClass);
        Integer subjectId = subjectIdMap.get(selectedSubject);
        
        Map<String, Object> statistics =
            gradeService.getGradeStatistics(classId, subjectId, examType);
        
        DecimalFormat df = new DecimalFormat("#.##");
        
        for (Map.Entry<String, Object> entry : statistics.entrySet()) {
            Map<String, Object> stats = (Map<String, Object>) entry.getValue();
            Object[] rowData = {
                entry.getKey(),
                stats.get("count") + "人 (" + df.format(stats.get("percentage")) + "%)",
                df.format(stats.get("maxScore")),
                df.format(stats.get("minScore")),
                df.format(stats.get("avgScore")),
                df.format(stats.get("passRate")) + "%"
            };
            tableModel.addRow(rowData);
        }
    }
} 